<template>
  <div class="dcs-container">
    <!-- Page Title Tabs (Assuming these are handled by a parent layout/component) -->
    <!-- <div class="dcs-page-tabs"> ... </div> -->

    <div class="dcs-grid-layout">
      <!-- 第一列：两个表格卡片 -->
      <div class="dcs-column">
        <!-- 钢种统计 -->
        <div class="dcs-grid-item dcs-card">
          <div class="dcs-card-header">
            <span>钢种统计</span>
            <div class="dcs-header-buttons">
              <el-button-group size="small">
                <el-button :type="topLeftDateRange === 'day' ? 'primary' : 'default'"
                  @click="topLeftDateRange = 'day'">按日</el-button>
                <el-button :type="topLeftDateRange === 'week' ? 'primary' : 'default'"
                  @click="topLeftDateRange = 'week'">按周</el-button>
                <el-button :type="topLeftDateRange === 'month' ? 'primary' : 'default'"
                  @click="topLeftDateRange = 'month'">按月</el-button>
              </el-button-group>
            </div>
          </div>
          <div class="dcs-card-body">
            <el-table :data="steelGradeTableData" size="small" border height="180"
              :header-cell-style="tableHeaderStyle">
              <el-table-column prop="steelGrade" label="钢种" width="150" />
              <el-table-column prop="totalCount" label="总卷数" width="100" />
              <el-table-column prop="flag1Count" label="跑偏卷数" width="100" />
              <el-table-column prop="flag1Ratio" label="跑偏率" width="100">
                <template #default="scope">{{ Number(scope.row.flag1Ratio).toFixed(3) }}</template>
              </el-table-column>
              <el-table-column prop="flag2Count" label="纠偏卷数" width="100" />
              <el-table-column prop="flag2Ratio" label="纠偏率" width="100">
                <template #default="scope">{{ Number(scope.row.flag2Ratio).toFixed(3) }}</template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 跑偏原因分类 -->
        <div class="dcs-grid-item dcs-card">
          <div class="dcs-card-header">
            <span>品规统计</span>
            <div class="dcs-header-buttons">
              <el-select v-model="midLeftReasonClass" placeholder="跑偏原因分类" size="small"
                style="width: 140px; margin-right: 10px;">
                <el-option label="分类 A" value="A"></el-option>
                <el-option label="分类 B" value="B"></el-option>
              </el-select>
              <el-button-group size="small">
                <el-button :type="midLeftDateRange === 'day' ? 'primary' : 'default'"
                  @click="midLeftDateRange = 'day'">按日</el-button>
                <el-button :type="midLeftDateRange === 'week' ? 'primary' : 'default'"
                  @click="midLeftDateRange = 'week'">按周</el-button>
                <el-button :type="midLeftDateRange === 'month' ? 'primary' : 'default'"
                  @click="midLeftDateRange = 'month'">按月</el-button>
              </el-button-group>
            </div>
          </div>
          <div class="dcs-card-body">
            <el-table :data="reasonClassTableData" size="small" border height="180"
              :header-cell-style="tableHeaderStyle">
              <el-table-column prop="gradeCode" label="钢种分档号" width="120" />
              <el-table-column prop="widthCode" label="宽度分档号" width="120" />
              <el-table-column prop="thickCode" label="厚度分档号" width="120" />
              <el-table-column prop="totalCount" label="总卷数" width="100" />
              <el-table-column prop="flag1Count" label="跑偏卷数" width="100" />
              <el-table-column prop="flag1Ratio" label="跑偏率" width="100">
                <template #default="scope">{{ Number(scope.row.flag1Ratio).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="flag2Count" label="纠偏卷数" width="100" />
              <el-table-column prop="flag2Ratio" label="纠偏率" width="100">
                <template #default="scope">{{ Number(scope.row.flag2Ratio).toFixed(2) }}</template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 第二列：两个柱形图卡片 -->
      <div class="dcs-column">
        <!-- 跑偏概率最高的几类品规（原因/位置） -->
        <div class="dcs-grid-item dcs-chart-card">
          <div class="dcs-card-header">
            <span>跑偏概率最高的几类品规</span>
            <div class="dcs-header-controls">
              <el-radio-group v-model="topRightChartType" size="small">
                <el-radio-button label="reason">跑偏原因</el-radio-button>
                <el-radio-button label="location">跑偏位置</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="dcs-chart" ref="topRightChartRef"></div>
        </div>
        <!-- 跑偏概率最高的几类品规（钢种/位置） -->
        <div class="dcs-grid-item dcs-chart-card">
          <div class="dcs-card-header">
            <span>跑偏概率最高的几类品规</span>
            <div class="dcs-header-controls">
              <el-radio-group v-model="midRightChartType" size="small">
                <el-radio-button label="steelGrade">钢种</el-radio-button>
                <el-radio-button label="location">跑偏位置</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="dcs-chart" ref="midRightChartRef"></div>
        </div>
      </div>

      <!-- 第三列：两个趋势图卡片 -->
      <div class="dcs-column">
        <!-- 钢种每日跑偏趋势图 -->
        <div class="dcs-grid-item dcs-chart-card">
          <div class="dcs-card-header">钢种每日跑偏趋势图</div>
          <div class="dcs-chart" ref="bottomLeftChartRef"></div>
        </div>
        <!-- 跑偏原因每日跑偏趋势图 -->
        <div class="dcs-grid-item dcs-chart-card">
          <div class="dcs-card-header">跑偏原因每日跑偏趋势图</div>
          <div class="dcs-chart" ref="bottomMidChartRef"></div>
        </div>
      </div>

      <!-- 结论卡片（跨列显示） -->
      <div class="dcs-grid-item dcs-card dcs-conclusion-card">
        <div class="dcs-card-header">结论</div>
        <div class="dcs-conclusion-content">
          <p>{{ conclusionText }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts/core';
import {
  BarChart,
  LineChart,
  BarSeriesOption,
  LineSeriesOption
} from 'echarts/charts';
import {
  TooltipComponent,
  GridComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import type { EChartsOption } from 'echarts';
import { ActualPerformanceRollDeviationApi } from '/@/api/deviationanalysis/ActualPerformanceRollDeviation';
import dayjs from 'dayjs';
// --- 跑偏原因分类统计数据 ---
interface ReasonClassStat {
  gradeCode: string;
  widthCode: string;
  thickCode: string;
  totalCount: string;
  flag1Count: string;
  flag2Count: string;
  flag1Ratio: string;
  flag2Ratio: string;
}
const reasonClassTableData = ref<ReasonClassStat[]>([]);
echarts.use([
  TooltipComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
  BarChart,
  LineChart,
  CanvasRenderer
]);

// --- Data Refs ---
const topLeftDateRange = ref('day');
const midLeftDateRange = ref('day');
const midLeftReasonClass = ref('A');
const topRightChartType = ref('reason');
const midRightChartType = ref('steelGrade');

const conclusionText = ref('结论内容：跑偏次数最多的是什么钢种，跑偏占比最多的是什么钢种，跑偏原因是什么，该类型跑偏呈现上升趋势，几号cpc跑偏次数最多，需重点关注');

// --- 钢种统计数据 ---
interface SteelGradeStat {
  steelGrade: string;
  totalCount: string;
  flag1Count: string;
  flag2Count: string;
  flag1Ratio: string;
  flag2Ratio: string;
}
const steelGradeTableData = ref<SteelGradeStat[]>([]);

const tableHeaderStyle = {
  background: '#eef1f6',
  color: '#606266',
  fontWeight: '500'
};

// --- Chart Refs and Instances ---
const topRightChartRef = ref<HTMLElement | null>(null);
const midRightChartRef = ref<HTMLElement | null>(null);
const bottomLeftChartRef = ref<HTMLElement | null>(null);
const bottomMidChartRef = ref<HTMLElement | null>(null);

let topRightChartInstance: echarts.ECharts | null = null;
let midRightChartInstance: echarts.ECharts | null = null;
let bottomLeftChartInstance: echarts.ECharts | null = null;
let bottomMidChartInstance: echarts.ECharts | null = null;

// --- Chart Options (Shared dark theme) ---
const getBaseChartOptions = (): EChartsOption => ({
  backgroundColor: '#fff',
  title: { show: false },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    backgroundColor: 'rgba(50,50,50,0.7)',
    borderColor: '#ccc',
    borderWidth: 1,
    textStyle: { color: '#303133' }
  },
  grid: {
    left: '10%',
    right: '8%',
    top: '15%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    axisLabel: { color: '#606266', fontSize: 10 },
    axisLine: { lineStyle: { color: '#dcdfe6' } },
    splitLine: { show: false }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#606266', fontSize: 10 },
    axisLine: { show: true, lineStyle: { color: '#dcdfe6' } },
    splitLine: { lineStyle: { color: '#e4e7ed', type: 'dashed' } }
  },
  textStyle: {
    color: '#303133'
  }
});

// --- 获取钢种统计数据并渲染表格和柱状图 ---
async function fetchSteelGradeStats(dateType = 'day') {
  let beginDate = dayjs().format('YYYY-MM-DD');
  let endDate = dayjs().format('YYYY-MM-DD');
  if (dateType === 'week') {
    beginDate = dayjs().startOf('week').format('YYYY-MM-DD');
    endDate = dayjs().endOf('week').format('YYYY-MM-DD');
  } else if (dateType === 'month') {
    beginDate = dayjs().startOf('month').format('YYYY-MM-DD');
    endDate = dayjs().endOf('month').format('YYYY-MM-DD');
  }
  const res = await ActualPerformanceRollDeviationApi.findHighestSteelGradeByDate({ beginDate, endDate });
  if (res && res.data && Array.isArray(res.data.data)) {
    steelGradeTableData.value = res.data.data;
    nextTick(() => initCharts());
  } else {
    steelGradeTableData.value = [];
    nextTick(() => initCharts());
  }
}

async function fetchSpecificationsStats(dateType = 'day') {
  let beginDate = dayjs().format('YYYY-MM-DD');
  let endDate = dayjs().format('YYYY-MM-DD');
  if (dateType === 'week') {
    beginDate = dayjs().startOf('week').format('YYYY-MM-DD');
    endDate = dayjs().endOf('week').format('YYYY-MM-DD');
  } else if (dateType === 'month') {
    beginDate = dayjs().startOf('month').format('YYYY-MM-DD');
    endDate = dayjs().endOf('month').format('YYYY-MM-DD');
  }
  const res = await ActualPerformanceRollDeviationApi.findHighestSpecificationsByDate({ beginDate, endDate });
  if (res && res.data && Array.isArray(res.data.data)) {
    reasonClassTableData.value = res.data.data;
    nextTick(() => initCharts());
  } else {
    reasonClassTableData.value = [];
    nextTick(() => initCharts());
  }
}
// --- Chart Initialization ---
const initCharts = () => {
  disposeCharts();
  // Top Right Chart (Bar) - 钢种跑偏率
  if (topRightChartRef.value) {
    topRightChartInstance = echarts.init(topRightChartRef.value);
    const categories = steelGradeTableData.value.map(i => i.steelGrade);
    const data = steelGradeTableData.value.map(i => Number(i.flag1Ratio));
    const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: categories },
      yAxis: { ...(getBaseChartOptions().yAxis as object), max: 1.0 },
      series: [{
        data: data,
        type: 'bar' as const,
        barWidth: '60%',
        itemStyle: { color: '#409EFF' },
        label: {
          show: true,
          position: 'top',
          formatter: (params) => Number(params.value).toFixed(2),
          color: '#606266',
          fontSize: 9
        }
      }] as BarSeriesOption[]
    };
    topRightChartInstance.setOption(option as EChartsOption);
  }

  // Middle Right Chart (Bar) - Similar structure, potentially different data/categories
  if (midRightChartRef.value) {
    midRightChartInstance = echarts.init(midRightChartRef.value);
    const categories = reasonClassTableData.value.map(i => `${i.gradeCode}-${i.widthCode}-${i.thickCode}`);
    const data = reasonClassTableData.value.map(i => Number(i.flag1Ratio));
    const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: categories },
      yAxis: { ...(getBaseChartOptions().yAxis as object), max: 1.0 },
      series: [{
        data: data,
        type: 'bar' as const,
        barWidth: '60%',
        itemStyle: { color: '#67C23A' },
        label: {
          show: true,
          position: 'top',
          formatter: (params) => Number(params.value).toFixed(2),
          color: '#606266',
          fontSize: 9
        }
      }] as BarSeriesOption[]
    };
    midRightChartInstance.setOption(option as EChartsOption);
  }

  // Bottom Left Chart (Line) - Placeholder
  if (bottomLeftChartRef.value) {
    bottomLeftChartInstance = echarts.init(bottomLeftChartRef.value);
    const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, // Example categories
      yAxis: { ...(getBaseChartOptions().yAxis as object), name: '跑偏次数' },
      series: [
        {
          name: 'Steel Grade A',
          type: 'line' as const,
          smooth: true,
          data: [12, 5, 8, 15, 10, 20, 18],
          lineStyle: { color: '#E6A23C' } // Element Plus Orange
        },
        {
          name: 'Steel Grade B',
          type: 'line' as const,
          smooth: true,
          data: [8, 10, 6, 9, 14, 12, 11],
          lineStyle: { color: '#F56C6C' } // Element Plus Red
        }
      ] as LineSeriesOption[]
    };
    bottomLeftChartInstance.setOption(option as EChartsOption);
  }

  // Bottom Middle Chart (Line) - Placeholder
  if (bottomMidChartRef.value) {
    bottomMidChartInstance = echarts.init(bottomMidChartRef.value);
    const option = {
      ...getBaseChartOptions(),
      xAxis: { ...(getBaseChartOptions().xAxis as object), data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
      yAxis: { ...(getBaseChartOptions().yAxis as object), name: '跑偏次数' },
      series: [
        {
          name: 'Reason X',
          type: 'line' as const,
          smooth: true,
          data: [5, 15, 12, 8, 10, 9, 13],
          lineStyle: { color: '#909399' } // Element Plus Gray
        },
        {
          name: 'Reason Y',
          type: 'line' as const,
          smooth: true,
          data: [10, 3, 6, 11, 9, 16, 10],
          lineStyle: { color: '#b3e19d' } // Lighter Green
        }
      ] as LineSeriesOption[]
    };
    bottomMidChartInstance.setOption(option as EChartsOption);
  }
};

const disposeCharts = () => {
  topRightChartInstance?.dispose();
  midRightChartInstance?.dispose();
  bottomLeftChartInstance?.dispose();
  bottomMidChartInstance?.dispose();
  topRightChartInstance = null;
  midRightChartInstance = null;
  bottomLeftChartInstance = null;
  bottomMidChartInstance = null;
};

const handleResize = () => {
  topRightChartInstance?.resize();
  midRightChartInstance?.resize();
  bottomLeftChartInstance?.resize();
  bottomMidChartInstance?.resize();
};

// --- 监听日/周/月切换，自动请求数据 ---
watch(topLeftDateRange, (val) => {
  fetchSteelGradeStats(val);
  fetchSpecificationsStats(val);
});

// --- 生命周期 ---
onMounted(() => {
  fetchSteelGradeStats(topLeftDateRange.value);
  fetchSpecificationsStats(midLeftDateRange.value);
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  disposeCharts();
});

</script>

<style scoped>
.dcs-container {
  padding: 1vw;
  background-image: linear-gradient(to top, white, #e6f0ff);
  min-height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  font-family: 'Microsoft YaHei', sans-serif;
  overflow: hidden;
}

.dcs-grid-layout {
  flex-grow: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* 大屏最多3列 */
  grid-auto-rows: minmax(350px, auto);
  /* 卡片高度更高 */
  gap: 1.2vw;
  overflow: hidden;
  width: 100%;
  min-height: 0;
}

.dcs-column {
  display: flex;
  flex-direction: column;
  gap: 1.2vw;
  min-width: 0;
}

.dcs-grid-item {
  display: flex;
  flex-direction: column;
  border-radius: 4px;
  overflow: hidden;
  min-width: 0;
  min-height: 0;
  height: 100%;
  background: #fff;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}

.dcs-card,
.dcs-chart-card {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  min-width: 0;
  min-height: 280px;
  flex: 1 1 0%;
  display: flex;
  flex-direction: column;
}

.dcs-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5em 1em;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 1em;
  font-weight: 600;
  color: #303133;
  flex-shrink: 0;
  min-width: 0;
}

.dcs-header-buttons,
.dcs-header-controls {
  display: flex;
  align-items: center;
  gap: 0.5em;
  min-width: 0;
}

.dcs-card-body {
  padding: 0.7em;
  flex: 1 1 0%;
  overflow: auto;
  min-width: 0;
  min-height: 0;
  max-height: 38vh;
}

.dcs-chart {
  flex-grow: 1;
  min-height: 180px;
  min-width: 0;
}

.dcs-conclusion-content {
  padding: 1em;
  font-size: 0.95em;
  color: #606266;
  line-height: 1.6;
  flex-grow: 1;
  overflow-y: auto;
}

.dcs-conclusion-card {
  grid-column: 1 / -1;
  min-height: 80px;
  max-height: 18vh;
}

@media (max-width: 1100px) {
  .dcs-grid-layout {
    grid-template-columns: repeat(2, 1fr);
    /* 中等屏幕2列 */
    gap: 2vw;
  }

  .dcs-card-body {
    max-height: 30vh;
  }
}

@media (max-width: 700px) {
  .dcs-grid-layout {
    grid-template-columns: 1fr;
    /* 小屏1列 */
    gap: 3vw;
  }

  .dcs-card-header {
    font-size: 0.98em;
    padding: 0.5em 0.5em;
  }

  .dcs-card-body {
    max-height: 40vh;
  }
}
</style>
